package com.zjjt.dc.tools.download.file.config;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;

public class DownloadConfig {
    private static DownloadConfig instance;
    private Map<String, Object> config;

    private DownloadConfig() {
        loadConfig();
    }

    public static DownloadConfig getInstance() {
        if (instance == null) {
            instance = new DownloadConfig();
        }
        return instance;
    }

    @SuppressWarnings("unchecked")
    private void loadConfig() {
        try {
            Yaml yaml = new Yaml();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/tools/download.yml");
            if (inputStream != null) {
                config = yaml.load(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 如果加载失败，使用默认配置
            config = null;
        }
    }

    @SuppressWarnings("unchecked")
    public int getPoolSize() {
        if (config != null) {
            Map<String, Object> download = (Map<String, Object>) config.get("download");
            if (download != null) {
                Map<String, Object> pool = (Map<String, Object>) download.get("pool");
                if (pool != null) {
                    Object poolSize = pool.get("pool_size");
                    if (poolSize instanceof Number) {
                        return ((Number) poolSize).intValue();
                    }
                }
            }
        }
        // 默认线程池大小
        return 5;
    }


    public long getCheckInterval() {
        if (config != null) {
            Map<String, Object> download = (Map<String, Object>) config.get("download");
            if (download != null) {
                Map<String, Object> pool = (Map<String, Object>) download.get("pool");
                if (pool != null) {
                    Object poolSize = download.get("check_interval");
                    if (poolSize instanceof Number) {
                        return ((Number) poolSize).intValue();
                    }
                }
            }
        }
        // 默认等待时间（）秒
        return 60;
    }

    public long getIdleThreshold() {
        if (config != null) {
            Map<String, Object> download = (Map<String, Object>) config.get("download");
            if (download != null) {
                Map<String, Object> pool = (Map<String, Object>) download.get("pool");
                if (pool != null) {
                    Object iT = download.get("idle_threshold");
                    if (iT instanceof Number) {
                        return ((Number) iT).intValue();
                    }
                }
            }
        }
        // 默认最长空闲时间（）秒
        return 600;
    }
}